#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from src.db import db_meizi

__author__ = 'DB_BOY'

# https://www.mzitu.com/jiepai/comment-page-1/#comments

import time
import requests
from bs4 import BeautifulSoup

url = "http://www.mzitu.com/all"
pic = "http://www.mzitu.com/150343"


class Info(object):
    def __init__(self, url, title):
        self.url = url
        self.title = title


''' 获取html页面'''


def downHtml(url):
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240",
        'Connection': 'Keep-Alive',
        'Referer': "http://www.mzitu.com/150343"
    }
    return requests.get(url, headers=headers).text


''' 解析获取所有的妹子url  '''


def parseHtml(url):
    html = downHtml(url)
    soup = BeautifulSoup(html,features="html.parser")
    # print(soup)
    #
    list = soup.select("img[class='lazy']")
    for a in list:
        pic = a["data-original"].strip()
        print(str1,pic)
        # write_info(pic)


def write_info(info):
    connection = db_meizi().connectDB()
    try:
        with connection.cursor() as cursor:
            sql = 'select count(*) from zipai where info_url =%s'
            cursor.execute(sql, (info))
            result = cursor.fetchone()
            count = result[0]
            if (count > 0):
                print("--------------更新: ", info)
                # 事务提交
                cursor.close()
                return 0
            else:
                print("**************插入: ",str1, info)
                sql = 'insert into zipai(info_url) values(%s)'
                # 执行sql语句
                cursor.execute(sql, (info))
                connection.commit()
                # 事务提交
                cursor.close()
                return 1
    finally:
        # 关闭数据库连接
        connection.close()
        # print("-------------写入数据库结束--------------")


# 获取所有妹子的url
# html = downHtml(url)
# parseHtml(html)
str1=""
if __name__ == "__main__":
    # 获取所有妹子的url
    # parseHtml("https://www.mzitu.com/zipai/comment-page-448/#comment")
    #
    for i in range(2):
        str1 = str(i)
        parseHtml("https://www.mzitu.com/zipai/comment-page-"+str1+"/#comments")
    # 获取妹子所有的图片
